/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.enums.DeleteFlagEnum;
import com.pig4cloud.pigx.shop.api.entity.Article;
import com.pig4cloud.pigx.shop.api.entity.ArticleCategory;
import com.pig4cloud.pigx.shop.api.entity.ArticleContent;
import com.pig4cloud.pigx.shop.api.vo.ArticleVO;
import com.pig4cloud.pigx.shop.mapper.ArticleMapper;
import com.pig4cloud.pigx.shop.service.ArticleCategoryService;
import com.pig4cloud.pigx.shop.service.ArticleContentService;
import com.pig4cloud.pigx.shop.service.ArticleService;
import com.pig4cloud.pigx.shop.service.GoodsMaterialService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 文章管理
 *
 * @author pig code generator
 * @date 2023-11-14 16:38:49
 */
@Service
@AllArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

	private final ArticleContentService articleContentService;

	private final ArticleCategoryService articleCategoryService;

	private final GoodsMaterialService materialService;

	/**
	 * 分页获取数据
	 * @param page
	 * @param article
	 * @return
	 */
	@Override
	public IPage<ArticleVO> getPage(Page page, Article article) {
		IPage<ArticleVO> result = new Page<>();

		LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
		if (!StringUtils.isEmpty(article.getArticleTitle())) {
			lqw.like(Article::getArticleTitle, article.getArticleTitle());
		}

		if (article.getCategoryId() != null) {
			lqw.eq(Article::getCategoryId, article.getCategoryId());
		}

		if (!StringUtils.isEmpty(article.getStatus())) {
			lqw.eq(Article::getStatus, article.getStatus());
		}
		lqw.orderByDesc(Article::getCreateTime);
		IPage<Article> items = this.page(page, lqw);

		if (items.getRecords().size() > 0) {
			List<Long> ids = new ArrayList<>();
			result = items.convert(u -> {
				ArticleVO v = new ArticleVO();
				BeanUtils.copyProperties(u, v);
				ids.add(u.getCategoryId());
				return v;
			});

			LambdaQueryWrapper<ArticleCategory> lqwArticleCategory = new LambdaQueryWrapper<>();
			lqwArticleCategory.in(ArticleCategory::getId, ids);
			List<ArticleCategory> articleCategoryList = articleCategoryService.list();
			result.getRecords().forEach(item -> {
				Optional<ArticleCategory> data = articleCategoryList.stream()
						.filter(p -> p.getId().longValue() == item.getCategoryId().longValue()).findFirst();
				if (data.isPresent()) {
					item.setCategoryName(data.get().getCategoryName());
				}
			});

		}

		return result;
	}

	/**
	 * 添加文章
	 * @param articleVO
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean add(ArticleVO articleVO) {
		// 保存文章信息
		Article article = new Article();
		BeanUtils.copyProperties(articleVO, article);
		this.save(article);

		// 保存文章内容
		ArticleContent articleContent = new ArticleContent();
		articleContent.setArticleId(article.getId());
		articleContent.setArticleContent(articleVO.getContent());
		articleContentService.save(articleContent);
		return true;
	}

	/**
	 * 获取文章信息
	 * @param id
	 * @return
	 */
	@Override
	public ArticleVO getInfoById(Long id) {
		ArticleVO result = new ArticleVO();
		Article article = this.getById(id);
		BeanUtils.copyProperties(article, result);
		if (!StringUtils.isEmpty(result.getArticleImages())) {
			result.setArticleImages(materialService.convertImageIdToUrl(result.getArticleImages()));
		}
		if (!StringUtils.isEmpty(result.getArticleHeader())) {
			result.setArticleHeader(materialService.convertImageIdToUrl(result.getArticleHeader()));
		}

		// 获取内容
		LambdaQueryWrapper<ArticleContent> lqw = new LambdaQueryWrapper<>();
		lqw.eq(ArticleContent::getArticleId, article.getId());
		lqw.eq(ArticleContent::getDelFlag, DeleteFlagEnum.VALID.getType());
		ArticleContent articleContent = articleContentService.getOne(lqw);
		result.setContent(articleContent.getArticleContent());
		return result;
	}

	/**
	 * 更新文章信息
	 * @param articleVO
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean update(ArticleVO articleVO) {
		Article article = new Article();
		BeanUtils.copyProperties(articleVO, article);
		this.updateById(article);

		LambdaQueryWrapper<ArticleContent> lqw = new LambdaQueryWrapper<>();
		lqw.eq(ArticleContent::getArticleId, article.getId());
		lqw.eq(ArticleContent::getDelFlag, DeleteFlagEnum.VALID.getType());
		ArticleContent articleContent = articleContentService.getOne(lqw);
		articleContent.setArticleContent(articleVO.getContent());
		articleContentService.updateById(articleContent);

		return true;
	}

}
